package bdz.projects.cbt.core
{
	import bdz.common.events.DispatchChannel;
	import bdz.common.utils.ArrayUtils;
	
	import flash.events.EventDispatcher;
	public class CBTProducts extends EventDispatcher{
		private static var instance:CBTProducts;
		private var _productList:Array;
		private var _channel:DispatchChannel = DispatchChannel.getChannel();
		private var _currentPList:Array;
		public function CBTProducts(se:SingletonEnforcer){
			super();
		}
		public static function getInstance(xlist:XMLList = null):CBTProducts{
			if(instance == null){
				instance = new CBTProducts(new SingletonEnforcer());
				instance.initializeComponent(xlist);
			}
			return instance;
		}
		private function shuffle():Array{
			var copy:Array = _productList.slice();
			
			var rnd:Number = Math.floor(Math.random()*4)
			var shuffled:Array = ArrayUtils.shuffle(copy);
			
			var counter:Number = 0;
			
			for(var i:Number = 0;i<rnd;i++){
				Math.floor(Math.random()*2) ? shuffled.pop() : shuffled.shift();
			}
			shuffled.sortOn("index", Array.NUMERIC);
			
			return shuffled;
		}
		private function initializeComponent(xlist:XMLList):void{
			_productList = new Array();
			for each(var xm:XML in xlist){
				var product:CBTProduct = new CBTProduct(xm);
				_productList.push(product);
			}
			
		}
		public function findProduct(str:String):CBTProduct{
			for each(var p:CBTProduct in _currentPList){
				if(p.name == str){
					return p;
				}
			}
			return null;
		}
		
		public function get productList():Array{
			_currentPList = shuffle();
			return _currentPList;
		}
		
	}
}
internal class SingletonEnforcer {}